package server.bootstrap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.HttpServlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Hugh
 * @Date: 2020/6/1
 */
public abstract class BaseBootStrap {

    /**定义socket监听的端口号*/
    private int port = 8090;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    protected Map<String, HttpServlet> servletMap = new HashMap<String,HttpServlet>();
    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        //加载Servlet
        loadServlet();
        //可以初始化一些东西
        init();
        /*
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        while(true) {
            Socket socket = serverSocket.accept();
            doHandle(socket);
        }
    }

    /**
     * 抽象方法，提供给子类调用
     * @param socket socket
     */
    protected abstract void doHandle(Socket socket) throws Exception;

    protected abstract void init() throws Exception;

    protected abstract void loadServlet()throws Exception;

    /**
     * 加载解析web.xml，初始化Servlet
     */
    protected void commonloadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

}
